package com.clkj.sunhelp.mvp.seekhelpnew.list;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clkj.sunhelp.R;
import com.clkj.sunhelp.common.Constant;
import com.clkj.sunhelp.common.TipStr;
import com.clkj.sunhelp.mvp.base.BaseActivity;
import com.clkj.sunhelp.mvp.seekhelpnew.adapter.ListAdapterForQiuZhuItem;
import com.clkj.sunhelp.mvp.seekhelpnew.detail.ActivitySeekHelpDetail;
import com.clkj.sunhelp.mvp.seekhelpnew.domain.QzxxListItem;
import com.clkj.sunhelp.util.CommonUtil;
import com.clkj.sunhelp.util.Res;
import com.clkj.sunhelp.util.ToastUtil;
import com.clkj.sunhelp.util.schedulers.SchedulerProvider;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jakewharton.rxbinding.view.RxView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by Administrator on 2017/3/30.
 */

public class ActivitySeekHelpToCiShanPage extends BaseActivity implements PullToRefreshBase.OnRefreshListener2, SeekHelpListContract.View {

    private PullToRefreshListView lv;
    private ListView originalLv;
    private RelativeLayout layoutEmpty;
    private TextView tvEmptytip;


    boolean isRefresh = false;
    boolean canLoad = false;
    Integer mPageIndex;

    String mSearchParams;

    private List<HashMap<String, Object>> mDataList = new ArrayList<HashMap<String, Object>>();

    List<QzxxListItem> mQiuZhuList = new ArrayList<>();
    ListAdapterForQiuZhuItem mAdapter;

    SeekHelpListContract.Presenter mPresenter;

    Handler mDealHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SeekHelpListPresenter.TYPE_DATA_NO_MORE:
                    canLoad = false;
                    lv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

                    if (mQiuZhuList.size() == 0) {
                        lv.setEmptyView(layoutEmpty);
                    } else {
                        ToastUtil.show(ActivitySeekHelpToCiShanPage.this, "已经获取全部数据", 2000);
                    }


                    break;
                case SeekHelpListPresenter.TYPE_DATA_HAS_DATA:

                    List<QzxxListItem> qiuZhuInfoList = (List<QzxxListItem>) msg.obj;

                    for (QzxxListItem qzr : qiuZhuInfoList) {
                        HashMap<String, Object> item = new HashMap<String, Object>();
                        item.put("row_id", qzr.getRow_id());
                        item.put("title", qzr.getTitle());
                        item.put("imgurl", qzr.getImgurl());
                        mDataList.add(item);
                    }

                    lv.onRefreshComplete();

                    if (isRefresh) {
                        mQiuZhuList.clear();
                        isRefresh = false;
                    }
                    if (qiuZhuInfoList.size() > 0) {
                        if (qiuZhuInfoList.size() >= Constant.DEFAULT_PAGE_SIZE) {
                            lv.setMode(PullToRefreshBase.Mode.BOTH);
                            canLoad = true;
                        } else {
                            canLoad = false;
                            lv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        }
                        mQiuZhuList.addAll(qiuZhuInfoList);

                    } /*else {

                    }*/

                    mAdapter.notifyDataSetChanged();


                    break;
                case SeekHelpListPresenter.TYPE_DATA_EXCEPTION:
                    lv.onRefreshComplete();
                    ToastUtil.showShort(ActivitySeekHelpToCiShanPage.this, TipStr.TIP_SERVER_GET_DATA_WRONG);
                    if (isRefresh) {
                        mQiuZhuList.clear();
                        lv.setEmptyView(layoutEmpty);

                    }

                    isRefresh = false;
                    canLoad = false;

                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seek_help_new);
        initTitleWithRightTvOrIv(null, null, "求助信息", true, "我要求助", null);
        initData();
        assignView();
        initView();

        mPresenter = new SeekHelpListPresenter(this, SchedulerProvider.getInstance(), mDealHandler);
        getOriginalList();
    }

    @Override
    public void initData() {
        mSearchParams = "hstrue";
    }

    @Override
    public void assignView() {

        lv = (PullToRefreshListView) findViewById(R.id.lv);
        originalLv = lv.getRefreshableView();
        layoutEmpty = (RelativeLayout) findViewById(R.id.layout_empty);
        tvEmptytip = (TextView) findViewById(R.id.tv_emptytip);
    }

    @Override
    public void initView() {
        lv.setOnRefreshListener(this);
        lv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        mAdapter = new ListAdapterForQiuZhuItem(mQiuZhuList, this);
        originalLv.setAdapter(mAdapter);

        RxView.clicks(tvRight)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        showToCiShanNetSeekHelpDialog();
                    }
                });

        originalLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String, Object> m_qzrinfo = (HashMap<String, Object>) mDataList
                        .get((position - 1));
                // logger.debug("oooooooobj:"+tmp);
                Intent itent1 = new Intent(getApplicationContext(),
                        ActivitySeekHelpDetail.class);
                Bundle mBundle = new Bundle();
                mBundle.putSerializable("m_qzrinfo", m_qzrinfo);
                itent1.putExtras(mBundle);
                startActivity(itent1);
            }
        });



    }

    private void getOriginalList() {
        isRefresh = true;
        int offset = 0;
        getQiuZhuInfoList(0, Constant.DEFAULT_PAGE_SIZE, mSearchParams);

    }

    private void getMoreList() {
        if (canLoad) {
            int offset = mQiuZhuList.size();
            getQiuZhuInfoList(mQiuZhuList.size(), Constant.DEFAULT_PAGE_SIZE, mSearchParams);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getOriginalList();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getMoreList();
    }

    @Override
    public void getQiuZhuInfoList(int offset, int maxSize, String params) {
        mPresenter.getQiuZhuInfoList(offset, maxSize, params);
    }

    @Override
    public void onGetQiuZhuInfoListSuccess(List<QzxxListItem> qiuZhuInfoList) {

    }

    @Override
    public void onGetQiuZhuInfoListError(String tip) {

    }

    @Override
    public void setPresenter(SeekHelpListContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        showProgressDialog(false,null);
    }

    @Override
    public void dismissLoading() {
        dismissProgressDialog();
    }


    private void showToCiShanNetSeekHelpDialog()
    {

        String originalStr = "请到淮安慈善网进行求助操作，网址是：http://www.haciai.cn";

        SpannableString aimSpanStr = CommonUtil.getAimTextColorSpannableStr(originalStr, Res.getColor(R.color.graydark),Res.getColor(R.color.color_main),0,17);
        new AlertDialog.Builder(this).setTitle("提示")
                .setMessage(aimSpanStr)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent= new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse("http://www.haciai.cn");
                        intent.setData(content_url);
                        startActivity(intent);
                    }
                }).setNegativeButton("取消",null).create().show();
    }
}
